package com.tidu.secret.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * AES加密工具类
 */
public class AESUtil {
    
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String DEFAULT_KEY = "MySecretKey12345"; // 16字节密钥
    
    /**
     * 生成AES密钥
     */
    public static String generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());
    }
    
    /**
     * 使用默认密钥加密
     */
    public static String encrypt(String plainText) throws Exception {
        return encrypt(plainText, DEFAULT_KEY);
    }
    
    /**
     * AES加密
     */
    public static String encrypt(String plainText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return Base64.encodeBase64String(encryptedBytes);
    }
    
    /**
     * 使用默认密钥解密
     */
    public static String decrypt(String encryptedText) throws Exception {
        return decrypt(encryptedText, DEFAULT_KEY);
    }
    
    /**
     * AES解密
     */
    public static String decrypt(String encryptedText, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.decodeBase64(encryptedText));
        return new String(decryptedBytes, "UTF-8");
    }
    
    /**
     * 格式化加密后的文本，用括号标记这是AES加密
     */
    public static String formatEncryptedText(String encryptedText) {
        return "[AES:" + encryptedText + "]";
    }
    
    /**
     * 从格式化的文本中提取加密内容
     */
    public static String extractEncryptedText(String formattedText) {
        if (formattedText.startsWith("[AES:") && formattedText.endsWith("]")) {
            return formattedText.substring(5, formattedText.length() - 1);
        }
        return formattedText;
    }
}